package com.csdj.t309springboot.common;

import com.csdj.t309springboot.constant.WebResultConstant;
import com.csdj.t309springboot.utils.MessageUtil;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class WebResult {
    private int code;
    private String msg;
    private Map<String,Object> result = new HashMap<>();

    public WebResult(){}

    public WebResult(int code){
        this.code = code;
        this.msg = MessageUtil.getMsg(code);
    }

    public WebResult(int code, Locale lang){
        this.code = code;
        this.msg = MessageUtil.getMsg(code,lang);
    }

    public WebResult(int code,Object data){
        this.code = code;
        this.msg = MessageUtil.getMsg(code);
        this.result.put("data",data);
    }

    public WebResult(Object obj){
        if(obj == null){
            this.code = WebResultConstant.NO_DATA;
            this.msg = MessageUtil.getMsg(this.code);
        }else{
            if(obj instanceof Boolean){
                boolean res = (boolean) obj;
                if(res){
                    this.code = WebResultConstant.SUCCESS;
                    this.msg = MessageUtil.getMsg(this.code);
                }else{
                    this.code = WebResultConstant.FAIL;
                    this.msg = MessageUtil.getMsg(this.code);
                }
            }else{
                this.code = WebResultConstant.SUCCESS;
                this.msg = MessageUtil.getMsg(this.code);
                this.result.put("data",obj);
            }
        }

    }

    public static WebResult success(Object data){
        return new WebResult(WebResultConstant.SUCCESS,data);
    }

    public static WebResult fail(int code){
        return new WebResult(code);
    }

    public static WebResult fail(int code,Locale lang){
        return new WebResult(code,lang);
    }

    public WebResult putData(String key,Object data){
        this.result.put(key,data);
        return this;
    }


    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getResult() {
        return result;
    }

    public void setResult(Map<String, Object> result) {
        this.result = result;
    }
}